package org.exmaple.springframework.beans.factory.support;

import org.exmaple.springframework.beans.factory.BeanFactory;
import org.exmaple.springframework.beans.BeansException;
import org.exmaple.springframework.beans.factory.config.BeanDefinition;

import java.util.Objects;

/**
 * @author DeYou
 * @date 2022/10/27
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {
    @Override
    public Object getBean(String beanName) {

        return doGetBean(beanName,null);
    }



    @Override
    public Object getBean(String beanName, Object... args) throws BeansException {
        return doGetBean( beanName,args );
    }

    protected <T> T  doGetBean(final String beanName, final Object[] args) {
        Object bean = getSingleton( beanName );
        if(Objects.nonNull(bean)){
            return (T)bean;
        }
        BeanDefinition beanDefinition = getBeanDefinition( beanName );
        return (T)createBean( beanDefinition,beanName,args );
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean( BeanDefinition beanDefinition,String beanName, Object[] args) throws BeansException;
}